app.controller('homePageCtrl', function($scope, $http, $myconfig, $mydialog, $ionicSideMenuDelegate, $interval, $rootScope, BthSevice, $state, $ionicHistory, PopupService, $ionicLoading, $timeout, SPAService) {

    $rootScope.$on('restoreSPA', function (event, data) {
        $rootScope.start == true; //此处是app挂掉后重新打开自动跳转到保养页面
        var every = 100 / data.typeTime;
        if(data.type == 'nose'){
            $rootScope.Bgb_time = data.typeTime; //保养时间
            $rootScope.connected = true;
            SPAService.coryzaData.mode = data.mode;
            SPAService.coryzaData.backtime = new Date().getTime() - (data.typeTime - data.ts) * 1000; //总时间-剩余时间=已保养时间  当前时间减已保养时间回到开始的时间
            SPAService.coryzaData.ts = data.typeTime; //剩余保养时间
            SPAService.coryzaData.stateText = data.stateText; //保养按钮状态
            SPAService.coryzaData.rotateCount = 45; //已保养时间的角度
            SPAService.coryzaData.progress = 1; //任意>0数
            SPAService.coryzaData.type = data.spa_type; //任意>0数
            console.log(SPAService.coryzaData);
            $state.go('app.Coryza', {type: data.spa_type});
            setSchedule(data.ts * 1000, data.mode); //开启本地通知,规定的时间完成后本地通知完成

        }else{
            $rootScope.Yzb_time = data.typeTime; //保养时间
            $rootScope.connected = true;
            SPAService.upKeepData.mode = data.mode;
            SPAService.upKeepData.backtime = new Date().getTime() - (data.typeTime - data.ts) * 1000;
            SPAService.upKeepData.ts = data.typeTime; //总保养时间
            SPAService.upKeepData.stateText = data.stateText; //保养按钮状态
            SPAService.upKeepData.rotateCount = 45;
            // SPAService.upKeepData.progress = every * (data.typeTime - data.ts); //任意>0数
            SPAService.upKeepData.progress = 1; //任意>0数
            SPAService.upKeepData.type = data.spa_type; //任意>0数
            // SPAService.upKeepData.backcount = data.typeTime - data.ts; //执行了多长时间
            $state.go('app.UpKeeping', {type: data.spa_type});
            setSchedule(data.ts * 1000, data.mode); //开启本地通知,规定的时间完成后本地通知完成
        }

        console.log('恢复保养：');
        console.log(data);
    });
    function setSchedule(time, mode) {
        if(device.platform == 'Android'){ //安卓的走这个插件的本地通知
            cordova.plugins.notification.local.schedule({
                id: 1001,
                title: '健康保养',
                text: '您正在进行的' + mode + '保养已完成。',
                at: new Date().getTime() + time,
                // badge: 1,
                autoClear: true, //默认值
                sound: 'res://platform_default', //默认值
                // sound: 'file://sounds/message.mp3',
                icon: 'res://drawable-xxxhdpi/icon.png', //默认值
                ongoing: false //默认值
            });
        }else {
            window.plugins.jPushPlugin.addLocalNotificationForIOS(
                time / 1000,
                '您正在进行的' + $rootScope.mode + '保养已完成。',
                1,
                "1000", {"key":"value"}
            );
        }

    }

    $scope.userMes = JSON.parse(localStorage.getItem('user'));

    //打开浏览器
    $scope.openBow = function() {
        $http.get($myconfig.api.base_host + '/basicinformation/list_APP')
            .then(function(res) {
                if (res.data.success) {
                    cordova.InAppBrowser.open(res.data.data.devicesales.flagshipurl, '_system', 'location=no,toolbar=yes,toolbarposition=top,closebuttoncaption=关闭');
                }
            });
        // window.open('http://baidu.com', '_system', 'location=yes');
    };

    // $rootScope.connected = true;

    $scope.slideOpen = false; //是否打开侧边栏
    $scope.toggleLeft = function() {
        $ionicSideMenuDelegate.toggleLeft();
        $scope.slideOpen = true;
        var timer = $interval(function() { // 设置个定时器判断侧边栏是否打开，如果是关闭状态则隐藏黑色透明蒙层
            if (!$ionicSideMenuDelegate.isOpen()) {
                $scope.slideOpen = false;
                $interval.cancel(timer);
            }
        }, 2000);
    };

    //红包活动请求
    $scope.redHove = function() {
        $http.get($myconfig.api.base_host + "/redpacket/redpacket_list_b?page=1&limit=1&distribution=app")
            .then(function(res) {
                $scope.redHoveData = res.data.data;
                console.log($scope.redHoveData);
                if ($scope.redHoveData[0].mainpic) {
                    $scope.RedBG = {
                        'background': 'url(' + $scope.redHoveData[0].posters + ') no-repeat 50% 50%',
                        'background-size': 'cover'
                    }
                }
            });
    };

    //定义默认能量值为0
    $scope.timeLong = 0;

    //用户累计签到天数获取
    // $scope.signSta = function(){
    //     $http.get($myconfig.api.base_host + '/signlogs/sign_days?user_id=' + $scope.userMes.id)
    //     .then(function(res){
    //         $scope.signStaData = res.data.data;
    //     });
    // };
    //设置默认显示滑动框
    $scope.myActiveSlide = 0;
    // 设置默认设备名
    $scope.device_name = '金鼻光';

    //定义饼形图渲染元素
    var myChart;

    //定义执行渲染请求优先级
    var is_up = 0;

    var option = {};

    //切花饼形图时执行更新数据
    $scope.slideHasChanged = function(index){
        // console.log($scope.myActiveSlide);
        is_up = index;
        if(index == 0){
            myChart = echarts.init(document.getElementById('main11'));
            $scope.device_name = '金鼻光';
        }else if(index == 1){
            $scope.device_name = '焕颜宝';
            myChart = echarts.init(document.getElementById('main12'));
        }
        // $timeout(function () {
            $scope.pieFor(myChart);
        // }, 500);
    };

    $rootScope.$on('loadData', function (event, data) {
        if(data == "on"){
            $timeout(function () {
                $scope.slideHasChanged(0);
            }, 1000);
        }
    });

    //用户设备使用情况饼形图编辑
    $scope.pieFor = function(MyChart) {
        if (MyChart) {
            myChart = MyChart;
        } else if (!MyChart) {
            myChart = echarts.init(document.getElementById('main11'));
        }
        $http.get($myconfig.api.base_host + '/physicallogs/count_mode?dev_name=' + $scope.device_name + '&user_id=' + $scope.userMes.id)
            .then(function(res) {
                //当前设备使用时长
                $scope.useDevTime = 0;
                if (res.data.data.length) {
                    for (var i = 0; i < res.data.data.length; i++) {
                        $scope.useDevTime += parseInt(res.data.data[i].durations) / 60;
                    }
                }
                if (res.data.data.length == 0 || !res.data.success) {
                    option = {
                        series: [{
                            name: '设备使用统计',
                            type: 'pie',
                            radius: ['0%', '65%'],
                            center: ['50%', '50%'],
                            labelLine: {
                                normal: {
                                    show: false
                                }
                            },
                            data: [{
                                value: 1,
                                name: '暂无数据',
                                itemStyle: {
                                    normal: {
                                        color: '#FEBD26',
                                        borderColor: '#FFF',
                                        borderWidth: 5
                                    }
                                }
                            }, ],

                            label: {
                                normal: {
                                    // formatter: '{d}%\n{b}',
                                    position: 'outside',
                                }
                            },
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }]
                    };
                } else if (res.data.data.length > 0) {

                    var data = [];
                    var color = ['#43DA78','#FA5252','#FEBD26','#1A1AE6'];
                    for(var i = 0; i<res.data.data.length; i++){
                        data.push({
                            value: res.data.data[i].durations,
                            name: res.data.data[i].mode,
                            itemStyle: {
                                normal: {
                                    color: color[i],
                                    borderColor: '#FFF',
                                    borderWidth: 5
                                }
                            }
                        });
                    }


                    option = {
                        series: [{
                            name: '设备使用统计',
                            type: 'pie',
                            radius: ['0%', '65%'],
                            center: ['50%', '50%'],
                            labelLine: {
                                normal: {
                                    show: false
                                }
                            },
                            data: data,

                            label: {
                                normal: {
                                    formatter: '{d}%\n{b}',
                                    position: 'outside',
                                }
                            },
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }]
                    };
                }
                /* else if (res.data.data.length == 2) {
                    option = {
                        series: [{
                            name: '设备使用统计',
                            type: 'pie',
                            radius: ['0%', '65%'],
                            center: ['50%', '50%'],
                            labelLine: {
                                normal: {
                                    show: false
                                }
                            },
                            data: [{
                                    value: res.data.data[0].durations,
                                    name: res.data.data[0].mode,
                                    itemStyle: {
                                        normal: {
                                            color: '#43DA78',
                                            borderColor: '#FFF',
                                            borderWidth: 5
                                        }
                                    }
                                },
                                {
                                    value: res.data.data[1].durations,
                                    name: res.data.data[1].mode,
                                    itemStyle: {
                                        normal: {
                                            color: '#FA5252',
                                            borderColor: '#FFF',
                                            borderWidth: 5

                                        }
                                    }
                                }
                            ],

                            label: {
                                normal: {
                                    formatter: '{d}%\n{b}',
                                    position: 'outside',
                                }
                            },
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }]
                    };
                } else if (res.data.data.length == 3) {
                    option = {
                        series: [{
                            name: '设备使用统计',
                            type: 'pie',
                            radius: ['0%', '65%'],
                            center: ['50%', '50%'],
                            labelLine: {
                                normal: {
                                    show: false
                                }
                            },
                            data: [{
                                    value: res.data.data[0].durations,
                                    name: res.data.data[0].mode,
                                    itemStyle: {
                                        normal: {
                                            color: '#43DA78',
                                            borderColor: '#FFF',
                                            borderWidth: 5
                                        }
                                    }
                                },
                                {
                                    value: res.data.data[1].durations,
                                    name: res.data.data[1].mode,
                                    itemStyle: {
                                        normal: {
                                            color: '#FA5252',
                                            borderColor: '#FFF',
                                            borderWidth: 5

                                        }
                                    }
                                },
                                {
                                    value: res.data.data[2].durations,
                                    name: res.data.data[2].mode,
                                    itemStyle: {
                                        normal: {
                                            color: '#FEBD26',
                                            borderColor: '#FFF',
                                            borderWidth: 5
                                        }
                                    }
                                }
                            ],

                            label: {
                                normal: {
                                    formatter: '{d}%\n{b}',
                                    position: 'outside',
                                }
                            },
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }]
                    };
                } else if (res.data.data.length == 4) {
                    option = {
                        series: [{
                            name: '设备使用统计',
                            type: 'pie',
                            radius: ['0%', '65%'],
                            center: ['50%', '50%'],
                            labelLine: {
                                normal: {
                                    show: false
                                }
                            },
                            data: [{
                                    value: res.data.data[0].durations,
                                    name: res.data.data[0].mode,
                                    itemStyle: {
                                        normal: {
                                            color: '#43DA78',
                                            borderColor: '#FFF',
                                            borderWidth: 5
                                        }
                                    }
                                },
                                {
                                    value: res.data.data[1].durations,
                                    name: res.data.data[1].mode,
                                    itemStyle: {
                                        normal: {
                                            color: '#FA5252',
                                            borderColor: '#FFF',
                                            borderWidth: 5

                                        }
                                    }
                                },
                                {
                                    value: res.data.data[2].durations,
                                    name: res.data.data[2].mode,
                                    itemStyle: {
                                        normal: {
                                            color: '#FEBD26',
                                            borderColor: '#FFF',
                                            borderWidth: 5
                                        }
                                    }
                                },
                                {
                                    value: res.data.data[3].durations,
                                    name: res.data.data[3].mode,
                                    itemStyle: {
                                        normal: {
                                            color: '#1A1AE6',
                                            borderColor: '#FFF',
                                            borderWidth: 5
                                        }
                                    }
                                },
                                // {value:135, name:'视频广告'}
                            ],

                            label: {
                                normal: {
                                    formatter: '{d}%\n{b}',
                                    position: 'outside',
                                }
                            },
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }]
                    };
                }*/
                // console.log(myChart);
                myChart.setOption(option);

            });
    };

    //判定当前设备类型是ios还是android
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    // alert('是否是Android：'+isAndroid);
    // alert('是否是iOS：'+isiOS);



    //跳转蓝牙连接界面
    $scope.linkdev = function() {
        if (isAndroid) {
            BthSevice.enable(); // 开启蓝牙
            // BthSevice.initialize(); //重新连接试试
            $ionicHistory.nextViewOptions({
                disableAnimate: true,
                disableBack: true,
                historyRoot: true
            });
            // $ionicSideMenuDelegate.toggleLeft();
            $state.go('app.MyLink');
        } else if (isiOS) {
            // BthSevice.initialize(); //重新连接试试
            $ionicHistory.nextViewOptions({
                disableAnimate: true,
                disableBack: true,
                historyRoot: true
            });
            $state.go('app.MyLink');
            // $state.go('app.guidance');
        }
    };

    //会员签到状态
    $scope.signlog = function() {
        /**
         * 注释人：jimmy
         * 注释时间： 2017年3月14日16:22:32
         * 内容：
         *      通过获取当前系统时间判断是上午还是下午
         * 由于后台数据不好判断签到状态未签到是上午未签到还是下午未签到
         * 所以讲当前系统时间的小时单独取出，与中午的12点整进行比较，
         * 如果小于13点则判断为上午时间，
         * 如果为大于中午12点，则判断为下午时间
         */
        var _date = new Date();
        var hour = _date.getHours();
        $http.get($myconfig.api.base_host + '/signlogs/status?user_id=' + $scope.userMes.id)
            .then(function(res) {
                // console.log(res.data.data);
                if (hour < 13 && res.data.data == 'Not_sign') {
                    res.data.data = 'Not_sign_up'
                } else if (hour > 12 && res.data.data == 'Not_sign' || hour > 12 && res.data.data == 'Am_sign') {
                    res.data.data = 'Not_sign_down'
                }
                $scope.signlog_data = res.data.data;
            });
    };



    //会员签到
    $scope.goSign = function() {
        $http.post($myconfig.api.base_host + '/signlogs/sign', {
            "user_id": $scope.userMes.id
        }).then(function(res) {
            // console.log(res.data.data);
            if (res.data.success) {
                $scope.success_text = '签到成功';
                $mydialog.success($scope);
                $scope.signlog();
                $http.get($myconfig.api.base_host + '/users/user_info?mobile=' + $rootScope._RootUser.mobile)
                    .then(function(res) {
                        if (res.data.success) {
                            localStorage.setItem('user', JSON.stringify(res.data.data))
                        }
                    });
            }
        });
    };



    //请求资讯列表
    $scope.newList = function() {
        $http.get($myconfig.api.base_host + '/news/news_list_b?page=1&limit=3')
            .then(function(res) {
                $scope.newListData = res.data.data;
                if ($scope.newListData[0].imgs[0]) {
                    $scope.BG = {
                        'background': 'url(' + $scope.newListData[0].imgs[0] + ') no-repeat 50% 50%',
                        'background-size': 'cover'
                    };
                }
            });
    };

    $scope.newList();



    if ($scope.userMes) {
        $scope.signlog();
        // $scope.signSta();
        $scope.redHove();
        $http.get($myconfig.api.base_host + '/users/user_info?mobile=' + $rootScope._RootUser.mobile)
            .then(function(res) {
                if (res.data.success) {
                    localStorage.setItem('user', JSON.stringify(res.data.data))
                }
            });
        // 如果用户所持有的设备不为空的化 则遍历当前设备数组并取出单个设备使用光能量相加
        if ($scope.userMes.modality.length) {
            for (var i = 0; i < $scope.userMes.modality.length; i++) {
                $scope.timeLong += Number($scope.userMes.modality[i].lightenergy);
                // console.log($scope.timeLong);
            }
        }
        // myChart.setOption(option);
    }
    // if(){
    // $ionicLoading.show({
    // template: 'Loading...'
    // });
    // }
    // console.log($rootScope.connected);
    $scope.$on('$ionicView.afterEnter', function() {
        $http.get($myconfig.api.base_host + '/basicinformation/list_APP')
            .then(function(res) {
                if (res.data.success) {
                    $scope.shopName = res.data.data.devicesales.flagshipname;
                }
            });
        // if ($rootScope.connected) {

            // console.log(document.getElementById('main11'))
        if(document.getElementById('main11')){
            $timeout(function () {
                myChart = echarts.init(document.getElementById('main11'));
                $scope.pieFor(myChart);
            }, 1000);
        }

        // }
        // $ionicLoading.hide();
    }, false);
});
